\chapter{Integrating Tapestry 5 and Google Web Toolkit}

The problem we want to solve is to integrate ``properly'' the two frameworks.
This has many interesring dimensions that developers may want to
consider: for example, what is a high level design process that can be used?
can we use an agile process ? is there any tool that can be used to have
live reloading of the applications both for \tap\ and \gwt\ at the same time?
how can we redner the components created with \gwt? how can we make them
seamlessy interact with \tap? and so on\ldots

In the following sections we present the different possibilities that we have
identified so far. In fact, the space of possible interactions between the two
is a continuum of solutions, and the one that will be implemented for a project
must be carefully chosen on the basis of the project requirements themselves.
The only common point is that \tap\ stays on the server side and \gwt\ 
components ``live'' in it.

One end of this continuum consists in \tap\ that loads an entire \gwt\
application as a single component in a page, basically \tap\ is the provider of
the {\it host} page. This is the least integrated solution, and is more in line
with the \gwt\ way of doing thins. In this case, \tap\ is used only a container
and the interaction between the two reduces to the rendering phase (which 
consists in render the DOM element hosting the whole application).

The other end of the continuum GWT components are used as any other javascript
components in \tap, i.e. they generate event requests, communicate with the
server via JSONObjects or JSONArray, and so on.

Finally, Mixins are not considered in this document, mainly because the
expressivness and richness of \gwt\, and Zones are not yet integrated mainly due
to the ability of \gwt\ to refresh asynchronously and \tap\ to produce partial
updates, and also because of it is not yet clear which benefits will brings to
the developers the inclusion of Zones. \Anote{This point is still open\ldots}

\section{Common points}
\begin{itemize}
  \item \gwt\ marks all its requests by setting the \textbf{Content-Type} to a
  special value that is ``text/x-gwt-rpc''.
  
\end{itemize}
\section{Integration via Dispatcher}
The first technique uses a Dispatcher, i.e. a service that is injected in the
normal request processing flow that waits for \gwt's request and handle them
without passing it to \tap. The basic idea is to take the original request,
decode it's payload using the \gwt\ facilities, recover the components to which
the request is directed to, and invoke one of its methods. The component
implements the interface of the RemoteService according to the \gwt-RPC
`standard'. The invocation is performed via the \gwt-RPC API and the return type
is automatically handled (an encoded reponse is generated by the API itself).
Once the dispatcher returns, the response is send back to the client.

\Anote{A summary of the benefits, limitations, drawbacks, expected usages, and
so on should be added here}

\section{Integration via Dispatcher \# 2}

This integration technique evolves and extends the first one by defining a new
annotation (@GWT) and by contributing to a series of services.
The annotation is defined in the tapestry-gwt-annotation project, while the
main code for the integration is defined in the tapestry-gwt-core project.

The services, modules and componetns that we defined for the integration are:
\begin{description}
  \item[GWTModule] service contains the currently contributed GWT modules, and
  stores the mappings between symbolic names of the modules with the packages
  that contain them.
  It accepts a configuration that maps GWT modules to a classpath and parses the
  gwt.xml file.
  
  GWTModule takes a mapped configuration consisting of module names and a path.
  This allows it to find the gwt.xml files and inform other services about a
  particular module.

  \item[GWTWorker] this class is contributed to the
  ComponentClassTransformWorker with constraint ``after:SetupRender''. Its job
  is to process the classes that are annotated with the GWT annotation by
  enabling the support of informal parameters, and adding or decorating the
  begin render method (indentified either by the @BeginRender annotation or by
  the naming convention) with an advice. 
  
  It rewrites components marked with @GWT. The worker rewrites the class to
  include the nocache.js javascript, creates the html body in which the client
  side can render and adds javascript to initialize the client side of the
  component. This eliminates the boiler plate code on the Tapestry side.
  
  The advice proceeds with the original
  invocation of the BeginRender method, which may be void, retrieves the
  MarkupWriter and the renders out:
	\begin{itemize}
	\item The {\tt script} tag poiting at the visualization library \Anote{Why not
	simply add this library with an Import statement?}.
	\item The {\tt script} tag containing the component namespace declaration,
	the global variable to be used to list all the components in the page, the
	global variable for the initialization parameters.
	\item The list of all the informal parameters passed to the orginial component
	that is rendering out.
	\item The {\tt div} tag that will be the host tag for the GWT component with
	its height parameter.
	\item The initialization script (via the JavaScriptSupport API) to contain the
	list of the components in the page.
	\end{itemize}
  
  \item[GWTEventDispatcher] extends Dispatcher and is contributed to
  MasterDispatcher with id ``gwtrpc'' and the constraint
  ``before:ComponentEvent''. This class identifies GWT requests as
  explained before, extracts from the URL of the request the tapestry component
  id, and finally extracts and decodes the request body using the
  RPCServletUtils API. The GWTEventDispatcher handles the requests by means of
  another service, the GWTEventHandler.
  
  This class process the URLs that represents component events in Tapestry
  terminology.
  GWTEventDispatcher looks for requests with a content type of "text/x-gwt-rpc".
  When it finds one it does the following:
  \begin{enumerate}
    \item Read request body with RPCServletUtils.readContentAsGwtRpc.
    \item Decode request with RPC.decodeRequest.
    \item Converts the url to a componentID by changing ". to ":" 
    \item Calls the GWTEventHandler 
  \end{enumerate} 
  
  \item[GWTEventHandler] service interface has only one method:
 	\begin{lstlisting}
public boolean handleRequest(
	String componentID,
	Response response,
	RPCRequest rpcRequest)
 	\end{lstlisting}

	This service locates and event hander in a page/component and calls it. This
	interface is implemented by the GWTEventHandlerImpl class.
  
  \item[GWTEventHandlerImpl] obtains a payload string by handling the response
  generated by Tapestry, encodes the payload, and then writes everything on the PrintWriter
  provided the original response object.
  If no payload is generated by Tapestry then the Handler return false that
  means the request was not handled. In this case, the original requests will be
  handled by the dispatcher sitting after the GWTEventDispatcher.
  
  The method to handle the event receives the componentID string and the
  rcpRequest class by the Dispatcher and does the following actions:
  \begin{enumerate}
  	\item Extract the methods to be invoked on the server class and all its
  	parameters;
  	\item Use the ComponentSource service to find the component with the given
  	componentID and check if that component contains a method that matches with
  	the one just extracted;
  	\item In case a matching method is found invoke it with the
  	parameters extracted before
  	\item Check if the method invokation produces any result. If an object is
  	returned that we consider the event as handled and we stop (i.e. we return
  	and produce the response);
  	\item If check fails, then we kinda {\it bubble} the event up in the
  	components hierarchy and we repeat the process until either we handle the
  	event or we get to the root. If we cannot find any matching method at
  	all, or any of the returns an Object, then we consider the event as not
  	handled and we return false (i.e. the GWTDispatcher did not handled the
  	request and we continue with the chain as describe before).
  \end{enumerate}
  
  The GWTEventHandler starts with the componentID and tries to find an event
  handler method. It progresses back up the tree until it finds one or reaches
  the page. When it finds a suitable method it calls it via reflection. If the
  method returns an object it will package up the object and return it to the
  client. If the method throws an exception it will return that to the client.
  This is different from the Google GWT RPC implementation in that you do not
  need to implement an interface. Also the Google implementation always calls
  the same method. This version finds methods associated with the page that
  loaded the GWT client.
  
  
  \Anote{Here is not clear to me what are the motivations of such a process. It
  seems that we are reproducing the whole logic of event bubbling that is
  already in the framework. The only added value that I see here is the fact
  that by crafting the component ID (if it is really possible altough) we can
  force different bubbling paths. But i do not know if that was really the
  intent. Two additional comments are: how can you manage void return types,
  for example in the chatter case stidy there are different method (signOn,
  signOff) that have a void return type on GWT side. How can you manage boolean
  return type ? If the GWT method has a boolean type, it seems that if the
  actual return value is true it will receive a reponse, nothing if that is
  false. I guess here we are mixing our assumptions on what the integration
  code should do when it encounters ``reserved'' return types, i.e. the ones
  that modify the behaviour of Tapestry, such as void/null/boolean/Object. We
  need to talk about this a bit more.}
  
  \item[GWTBindingFactory] service implements the BindingFactory interface.
  It creates new Bindings between GWTModule and location \Anote{I guess}.
  It works by creating new GWTBinding that extends the AbstractBinding class.
  This service is used to define the location of the module libraries to be
  inluded in pages. This service is contributted to BindingSource. This service
  implements {\tt gwt:} similar to {\tt asset:}.
  
  GWTBinding generates URLs for the various GWT modules. In order the load the
  module Javascript just use src="gwt:ModuleName". GWTBinding works with
  GWTModule/GWTScriptDispatcher to generate a url to a particular modules
  nocache.js file.
  
  \item[GWTScriptDispatcher] extends Dispatcher. Is contributed to
  MasterDispatcher with id ``gwtScript'' and the constraint ``before:Asset''.
  
  This class intercepts requests for GWTScripts that are identified by means of
  the GWTBindingFactory (see above). \Anote{At least\ldots I guess this
  is the case\ldots}, creates a virtualPath pointing to the right js asset and
  the inkove the GWTScriptHandler to handle the actual request.
  
  It looks for GWT script requests and routes them to the GWTScriptHander.
  The script dispatcher looks for requests for urls generated by the GWTBinding
  and routes them to the GWTScriptHander. Typically these start with /gwt.

  \item[GWTScriptHandler] service interface has only one method:\\
  public boolean handleRequest(String path) throws IOException;
  
  This interface is implemented by the GWTScriptHandlerImpl class. 
  
  The script handler returns the javascript generated by the GWT compiler. It
  finds the scripts in the classpath and returns them with the proper caching
  headers. With GWT all scripts but the nocache.js script may be cached forever
  by the browser.
  
  \item[GWTScriptHandlerImpl] builds the asseth path and uses the
  AssetResourceLocator service to obtain the request Resource. If the resource
  exists than it leverages the StreamResource service to send the reource back
  to the client and return true (request handled). Otherwise, let the pipeline
  to proceed (return false);
  
\end{description}

\Anote{Talking about the GWTModule service, this is what I was looking for, I
think is the right way to ``register'' gwt modules}

\Anote{Talking about the GWTScriptHandler service, this is great, it should
remove any pain in importing the gwt libraries, according to oue convention
about their placement. But I guess this can be contributed as well as the
other, maybe via the GWTModule service.}

\Anote{Talking about the EventHandling components my conclusions on this
integration: the work is good but it is not clear when it should be applied/in
which cases. I suspect that we can leverage on this approach if and when we
want to expose Tapestry services to the outside world. In this case, we cannot
rely on Components or Pages to handle the requests, thus we can  inject or
access on the fly the services that implements the ServiceInterface.  The issues
that I see here are: how can we identify the service to be invoked ?  Can we use
the machinery that is already there, like a RegistryLookUp or  something? How
can differentiate the GWT requests related to ComponentEvents  and ServiceEvents
(just invented the term) ? Can we use a Method annotation such  as GWT to
``expose'' methods to the outside world ? This is similar to the  approach taken
by DWR. And the case is the following, you have a service, some of  its methods
must be invokable without passing inside Tapestry pipelines, then  we can mark
them with the annotation, and modify the dispatcher (or something)  to lookup
from the marked service methods if it can find a matching method,  just like you
did for components ?}

\section{Integration via HttpServletFilter}
This technique uses a single HttpServletFilters\ldots to intercept the request,
and the response, just to encode and decode them from \gwt to \tap\ and the
other way around.

\Anote{Problems in managing void return types, Page/Block/Zone/redirect and
whatever. Some more description of experiences here\ldots}

\section{Integration via HttpServletFilter and ServiceAdvice}
The third technique extends and improves the previous one by adding a
ServiceAdvice to the HttpServletFilter. In this way the work can be clearly
divided in the processing of the request and the processing of the response.

The first step is to decode the orginal request before \tap\ can put its hands
on it (basically we want \tap\ to be agnostic to the kind of requests it
receives); the orginial request is a HttpServletRequest before \tap\ abstracts
it to a (shadow) service Request, thus it seemed to be resonable to intercept it
in the HttpServletPipeline. The filter job is to wrap the original (\gwt)
requests and enhance them by doing the following:
\begin{itemize}
    \item Add an header (X-Requested-With=``XMLHttpRequest") to force the
    request to be interpred by \tap\ as an AJAX request (see the isXHR() check in the AjaxFilter); 
  	\item Decode the request payload and ``re-encode'' them as context objects on
  	the request URL. This require a wrapper class around the original request.
  	The filter uses the facilities provided by \tap\ to perform this task (via
  	the EventContextEncoder service); \Anote{At the moment of writing I am
  	developing a slightly different approach for \tap\ 5.2 that consists in
  	providing directly the parameters as Request parameters and then using the
  	@InjectParameter(``name'') annotation to extract the on the component side.}
  	\item Let the request to flow in \tap\ as any other request.  
\end{itemize}

Once the request reaches the EventHandler method (either directly or via event
bubbling) the response is produced and it is processed by the 
ComponentEventResultProcessor as usual. At this point, the second part of the
integration takes place. The AjaxComponentEventProcessor is triggered and our
advice is used: the advice look the orginal request, if it is a \gwt\ request
then instead of the normal processing our modified version is used, and we can
encode (again) the response, and then send it back to the client.

\Anote{To make this working an additional modificationis required if the
context event object contains non default objects type. To translate these
objects and encode them on the URL we must provide the right TypeCoercions,
i.e. the rule to map the Object itself to the context string.}

\Anote{Possible evolution: use an anotation like the hibernate @Session to hide
this encoding/decoding process in something like a string hash on the URL or an
id that later is used to inject the value in the context. This will consists in
contributing the EventLinkEncoder and its decoder.}




